#!/bin/bash
#
# install.sh -- Recursively traverse each subdirectory under the current directory, execute make install, and package
#

# Install the package with make install to the specified directory and package it
# Define target directory and output directory
TARGET_DIR="/mnt/tinybpt/target"
BIN_DIR="/mnt/tinybpt/bin"
TREE_FILE="/mnt/tinybpt/tree.json"
ERROR_LOG="/mnt/tinybpt/install-error.log"

# Clear the target directory and output directory
rm -rf "$TARGET_DIR"/*
rm -rf "$BIN_DIR"/*

# Initialize tree.json file and error log file
echo "[" > "$TREE_FILE"
echo "" > "$ERROR_LOG"

# Traverse each subdirectory under the current directory
for dir in */ ; do
    if [ -d "$dir" ]; then
        echo "Processing $dir..."

        # Check if already compiled
        if [ ! -f "$dir/Makefile" ]; then
            echo "Skipping $dir: No Makefile found" >> "$ERROR_LOG"
            continue
        fi

        # Enter the subdirectory and execute make install, specifying the cross-compiler
        (cd "$dir" && make -j$(nproc) CC=riscv64-unknown-linux-gnu-gcc CXX=riscv64-unknown-linux-gnu-g++ install DESTDIR="$TARGET_DIR")
        if [ $? -ne 0 ]; then
            echo "Failed to install $dir" >> "$ERROR_LOG"
            continue
        fi

        # Generate directory structure and write to tree.json
        DIR_CONTENT=$(tree -J "$TARGET_DIR")
        echo "{\"version\": \"${dir%/}\", \"dir\": $DIR_CONTENT}," >> "$TREE_FILE"

        # Package the contents of the /mnt/tinybpt/target directory as subdirectory_name.tar.gz
        tar -cpvf "${dir%/}.tar.gz" -C "$TARGET_DIR" .

        # Move the package file to the /mnt/tinybpt/bin directory
        mv "${dir%/}.tar.gz" "$BIN_DIR"

        # Clear the /mnt/tinybpt/target directory
        rm -rf "$TARGET_DIR"/*
    fi
done

# Remove the last comma and close the JSON array
sed -i '$ s/,$//' "$TREE_FILE"
echo "]" >> "$TREE_FILE"

echo "All done!"